
import secrets
import time
import requests


def generate_cookie():
    # Generate parts of the cookie with appropriate random or static values
    __ac_nonce = secrets.token_hex(8)  # Similar length as your example
    # Starting with _02 followed by random
    __ac_signature = '_02' + secrets.token_hex(25)
    # Random token, adjusting length to match
    ttwid = f"1|{secrets.token_urlsafe(44)}"
    # Based on current time + random
    tt_webid = str(int(time.time())) + secrets.token_hex(5)
    msToken = secrets.token_urlsafe(50)  # Random token, length adjusted
    ttcid = secrets.token_hex(16)  # Random 32 character string
    tt_scid = secrets.token_hex(20)  # Random 40 character string
    # Prefix with 'verify_' + random
    s_v_web_id = 'verify_' + secrets.token_hex(20)

    # Concatenate all parts to form the full cookie string
    cookie_parts = [
        f'__ac_nonce={__ac_nonce}',
        f'__ac_signature={__ac_signature}',
        f'ttwid={ttwid}',
        f'tt_webid={tt_webid}',
        f'msToken={msToken}',
        f'ttcid={ttcid}',
        f'tt_scid={tt_scid}',
        f's_v_web_id={s_v_web_id}',
    ]
    out = '; '.join(cookie_parts)
    return out


cookies = generate_cookie()
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
    'Cookie': cookies
}


def download_video(url):
    file_name = "1.mp4"
    try:
        response = requests.get(url, headers=headers, timeout=60*5)
        print(response)
        if response.status_code == 200:
            print(f"数据大小: {len(response.content)}")
            with open(file_name, "wb") as f:
                f.write(response.content)
        else:
            return None
    except Exception as e:
        return None
    return file_name


if __name__ == '__main__':
    local_name = download_video('https://v11-cold.douyinvod.com/25545f52f2fb393ca5c9dfaf8b7419aa/66dc74f5/video/tos/cn/tos-cn-ve-15/ockAOfvakgq9DhHEQVmEAqBC8A2FIYXhm7GfEr/?a=1128&ch=0&cr=0&dr=0&cd=0%7C0%7C0%7C0&cv=1&br=1638&bt=1638&cs=0&ds=3&ft=LjVHEX998xsRu.0mD0P58lZW_3iXXggqxVJE1xWBlbPD-Ipz&mime_type=video_mp4&qs=0&rc=NmhpZmlmNmk2OTtoZDlmOUBpM3Vwcm05cmRpdTMzNGkzM0AuMTUvLV8uX2IxYjUyYl40YSM0Nl5jMmRrMGFgLS1kLS9zcw%3D%3D&btag=c0010e00098000&cquery=100y&dy_q=1725720258&feature_id=aa7df520beeae8e397df15f38df0454c&l=20240907224418D81A3DF5E898CBAC9424')
    print(local_name)
